<template>
    <transition enter-active-class="animate__animated animate__bounceInLeft">
        <div class="player" v-if="$root.musicStore.musicID" v-show="$root.isPlayer">
            <audio ref="audio" :src="`https://music.163.com/song/media/outer/url?id=${$root.musicStore.musicID}.mp3`" autoplay @timeupdate="timeUpdate" @pause="pause" @play="play" @ended="nextSong"></audio>
            <div class="playBar">
                <i ref="randImg">
                    <img :src="this.$root.musicStore.currentMusic.al.picUrl" alt="" v-if="this.$root.musicStore.currentMusic.al.picUrl"/>
                    <img src="../assets/img/music.png" alt="" v-else />
                </i>
                <i @click="isFullPage=true" v-html="$root.musicStore.currentMusic.name+artists"></i>
                <!--  v-swipeleft="prevSong" v-swiperight="nextSong" -->
                <i>
                    <canvas height="50" width="50" ref="processBtn" @click="changePlay"></canvas>
                </i>
            </div>
            <!-- 部分页全 -->
            <transition
                enter-active-class="animate__animated animate__slideInUp"
            >
            <div class="fullPage" v-show="isFullPage" >
                <div class="bg">
                    <img :src="this.$root.musicStore.currentMusic.al.picUrl" alt="" v-if="this.$root.musicStore.currentMusic.al.picUrl"/>
                    <img src="../assets/img/playBg.png" alt="" v-else />
                </div>
                <!-- 读针 -->
                <div class="needle" ref="needle"></div>
                <!-- 返回 -->
                <span @click="isFullPage=false,isPlayList=false,islyricFull=false" class="back iconfont iconback"></span>
                <!-- 收藏 -->
                <span class="like iconfont " :class="[ likeState ? 'iconicon_xihuan' : 'iconxihuan1']" @click="like"></span>
                <!-- 评论 -->
                <span class="comment iconfont iconpinglun" @click="toComment($root.musicStore.musicID)"></span>
                <!-- 碟子 -->
                <div class="songImg">
                    <span ref="songImg" @click="islyricFull=true">
                        <img :src="this.$root.musicStore.currentMusic.al.picUrl" alt="" v-if="this.$root.musicStore.currentMusic.al.picUrl"/>
                        <img src="../assets/img/music.png" alt="默认" v-else />
                    </span>
                </div>
                <!-- 歌词 -->
                <div class="lyric" :class="[islyricFull ? 'lyricFull' : '']" v-if="lyric" ref="lyric" @click="islyricFull=false">
                    <h3 v-html="$root.musicStore.currentMusic.name+artists" class="lyricTitle"></h3>
                    <div>
                        <ul :style="{transform:`translateY(-${moveTop}px)`}">
                            <li ref="lyricLi" v-for="(item,index) in lyric" :key="index" :class="{active:currentIndex==index}">{{item.lyric}}</li>
                        </ul>
                    </div>
                </div>
                <div class="nolyric" v-else>
                    <h3 class="lyricTitle" v-html="$root.musicStore.currentMusic.name+artists"></h3>
                    <p>抱歉！无法搜索到对应歌词！</p>
                </div>
                <div class="progress">
                    <i>{{currentTime | formatTime}}</i><input type="range" min="0" :max="duration" :value="currentTime" @change="changeTime"><i>{{duration | formatTime}}</i>
                </div>
                <div class="controlBar">
                    <!-- 图标 -->
                    <!-- 模式切换 -->
                    <span @click="playMode" class="iconfont icononly" v-if="playmode==1"></span>
                    <span @click="playMode" class="iconfont iconrandom" v-else-if="playmode==2"></span>
                    <span @click="playMode" class="iconfont iconlist" v-else></span>
                    <!-- 上一首 -->
                    <span @click="prevSong" class="iconfont iconprevSong" ></span>
                    <!-- 播放/暂停 -->
                    <span @click="changePlay" :class="[isPlay ? 'iconfont iconpause' : 'iconfont iconplay']" ></span>
                    <!-- 下一首 -->
                    <span @click="nextSong" class="iconfont iconnextSong" ></span>
                    <!-- 播放列表 -->
                    <span @click="isPlayList=true" class="iconfont iconplayList" ></span>
                </div>
                <!-- 播放列表数据 -->
                <div class="playList" v-if="$root.musicStore.musicList" :class=" [ isPlayList ? 'active' : '' ]">
                    <p>播放列表<span class="iconfont iconclose"  @click="isPlayList=false"></span></p>
                    <ul>
                        <li v-for="v in $root.musicStore.musicList" :key="v.id" v-html="v.name+'--'+v.ar[0].name" :style="{ color: v.id==$root.musicStore.musicID ? '#df3436' : ''}" @click="playMusic(v)"></li>
                    </ul>
                </div>
            </div>
            </transition>
        </div>
    </transition>
</template>

<script>
export default {
    name:'Play',
    data(){
        return{
            isPlay: true,
            isFullPage: false,
            duration: 0,
            currentTime: 0,
            artists: null,
            playmode: 3,
            isPlayList: false,
            currentIndex:0, //记录当前歌词播放的位置下标
            moveTop:0,
            islyricFull: false,  //歌词全屏
            lyric: null,
            likeState: null, //收藏
        }
    },
    updated(){
        // 同步歌手
        if(this.$root.musicStore.currentMusic.ar){
            this.artists = "<e calss='artists' style='color:#646566;font-size:12px;'>&nbsp;&nbsp;--&nbsp;&nbsp;"+this.$root.musicStore.currentMusic.ar[0].name+"</e>";
        }
        if(this.$root.musicStore.currentMusic.artists){
            this.artists = "<e calss='artists' style='color:#646566;font-size:12px;'>&nbsp;&nbsp;--&nbsp;&nbsp;"+this.$root.musicStore.currentMusic.artists[0].name+"</e>";
        }
    },
    methods:{
        // 切歌
        changeSong(){
            let currentIndex = 0;
            let musicList = this.$root.musicStore.musicList;
            if(this.playmode==2) return parseInt(musicList.length*Math.random());  //随机播放
            for(let i in musicList){
                if(musicList[i].id === this.$root.musicStore.musicID){
                    currentIndex = i;
                    break;
                }
            }
            return currentIndex;
        },
        // 放歌
        playMusic(item){
            this.$root.musicStore.musicID = item.id;
            this.$root.musicStore.currentMusic = item;
        },
        // 播放模式
        playMode(){
            // 1：单曲循环、2：随机播放、3：顺序播放
            this.playmode ++;
            this.playmode = this.playmode > 3 ? this.playmode = 1 : this.playmode;
        },
        // 上一首
        prevSong(){
            let currentIndex = this.changeSong();
            let musicList = this.$root.musicStore.musicList;
            if(this.playmode!=1) currentIndex--;  //单曲循环控制
            if(currentIndex<0){
                currentIndex = musicList.length-1;
            }
            this.$root.musicStore.musicID = musicList[currentIndex].id;
            this.$root.musicStore.currentMusic = musicList[currentIndex];
        },
        // 下一首
        nextSong(){
            let currentIndex = this.changeSong();
            let musicList = this.$root.musicStore.musicList;
            if(this.playmode!=1) currentIndex++;  //单曲循环控制
            if(currentIndex>musicList.length-1){
                currentIndex = 0;
            }
            this.$root.musicStore.musicID = musicList[currentIndex].id;
            this.$root.musicStore.currentMusic = musicList[currentIndex];
        },
        // 暂停
        pause(event){
            this.isPlay = true;
            this.changePlay();
            this.timeUpdate(event);
        },
        // 播放
        play(event){
            this.isPlay = false;
            this.changePlay();
            this.timeUpdate(event);
        },
        // 拉进度条
        changeTime(event){
            let time = event.target.value;
            this.currentTime = time;
            this.$refs.audio.currentTime = time;
        },
        // 切换状态
        changePlay(){
            if(this.isPlay){
                this.$refs.audio.pause();
                this.isPlay = false;
                this.$refs.randImg.style.animationPlayState = "paused";
                this.$refs.songImg.style.animationPlayState = "paused";
                this.$refs.needle.style.transform = "rotate(-30deg)";
            }else{
                this.$refs.audio.play();
                this.isPlay = true;
                this.$refs.randImg.style.animationPlayState = "running";
                this.$refs.songImg.style.animationPlayState = "running";
                this.$refs.needle.style.transform = "rotate(-10deg)";
            }
        },
        // 更新进度
        timeUpdate(event){
            let currentTime = event.target.currentTime;  //当前时间
            let duration = event.target.duration; //时间总长
            this.currentTime = currentTime;
            this.duration = duration;
            this.drawCircle(currentTime,duration);
            if(this.lyric){
                for(var i=0;i<this.lyric.length;i++){
                    if(i>=this.lyric.length-1){
                        this.currentIndex=i;
                        break;
                    }
                    if(this.lyric[i].time<=currentTime&&currentTime<this.lyric[i+1].time){
                        if(i>=2){
                            this.moveTop=this.$refs.lyricLi[i-2].offsetTop;
                        }else{
                            this.moveTop=0;
                        }
                        this.currentIndex=i;
                        break;
                    }
                }
            }
        },
        // 绘图函数
        drawCircle(currentTime,duration){
            let canvas = this.$refs.processBtn.getContext('2d');
            // 解决锯齿问题
            if (window.devicePixelRatio) {
                this.$refs.processBtn.style.width = "50px";
                this.$refs.processBtn.style.height = "50px";
                this.$refs.processBtn.height = 50 * window.devicePixelRatio;
                this.$refs.processBtn.width = 50 * window.devicePixelRatio;
                canvas.scale(window.devicePixelRatio, window.devicePixelRatio);
            }
            // 总进度绘制
            canvas.clearRect(0,0,50,50);
            canvas.save();
            canvas.beginPath();
            canvas.strokeStyle = "#fff";
            canvas.lineWidth = 4;
            canvas.arc(25,25,20,0,2*Math.PI);
            canvas.stroke();
            canvas.closePath();
            canvas.restore();
            // 当前进度绘制
            canvas.save();
            canvas.beginPath();
            canvas.strokeStyle = "#000";
            canvas.lineWidth = 4;
            canvas.arc(25,25,20,0,2*Math.PI*parseFloat(currentTime/duration));
            canvas.stroke();
            canvas.closePath();
            canvas.restore();
            // 播放暂停按钮绘制
            if(!this.isPlay){
                canvas.beginPath();
                canvas.moveTo(20,15);
                canvas.lineTo(35,25);
                canvas.lineTo(20,35);
                canvas.fill();
                canvas.closePath();
            }else{
                canvas.strokeStyle = "black";
                canvas.beginPath();
                canvas.moveTo(20,15);
                canvas.lineTo(20,35);
                canvas.stroke();
                canvas.closePath();
                canvas.beginPath();
                canvas.moveTo(30,15);
                canvas.lineTo(30,35);
                canvas.lineWidht = 10;
                canvas.stroke();
                canvas.closePath();
            }
        },
        // 喜欢
        like(){
            this.likeState = !this.likeState;
            let newLike = JSON.parse( window.localStorage.getItem('likeSongList'));
            if(newLike){
                if(this.likeState){
                    newLike.push(String(this.$root.musicStore.musicID));
                    newLike = Array.from(new Set(newLike));
                }else{
                    let index = newLike.indexOf(String(this.$root.musicStore.musicID));
                    newLike.splice(index,1);
                }
            }else{
                newLike = [];
                newLike.push(String(this.$root.musicStore.musicID));
            }
            window.localStorage.setItem('likeSongList',JSON.stringify(newLike));
        },
        // 评论
        toComment(id){
            this.isFullPage = false;
            this.$root.isPlayer = false;
            this.$router.push('/comment/'+id);
        },
        // 模拟手机滑动切歌
        
    },
    filters:{
        formatTime(val){
            if(val){
                let h = Math.floor( val/3600 ) < 10 ? "0"+Math.floor( val/3600 ) : Math.floor( val/3600 );
                let m = Math.floor( val%3600/60 ) < 10 ? "0"+Math.floor( val%3600/60 ) : Math.floor( val%3600/60 );
                let s = Math.floor( val%60 ) < 10 ? "0"+Math.floor( val%60 ) : Math.floor( val%60 );
                return `${h}:${m}:${s}`;
            }else{
                return "00:00:00";
            }
        }
    },
    computed:{
        musicIDs(){
            let musicID = this.$root.musicStore.musicID;
            return musicID;
        }
    },
    watch:{
        musicIDs(musicID){
            let likeList = JSON.parse( window.localStorage.getItem('likeSongList'));
            if(likeList){
                this.likeState = false;
                likeList.forEach( item => {
                    if(item == String(musicID)){
                        this.likeState = true;
                        return false;
                    }
                });
            }else{
                this.likeState = false;
            }
            this.$http.get('/lyric?id='+musicID).then(data =>{
                this.lyric = null;
                if(data.data.nolyric || !data.data.lrc) return false;
                if(data.data.lrc.lyric.indexOf('[00:00.000]')==-1) return false;
                let lyricArr = data.data.lrc.lyric.split('\n');
                lyricArr.pop();
                let reg = /\[(\d+):(\d+\.\d+)\](.*)/;
                let newLyric = lyricArr.map( item => {
                    if(reg.test(item)){
                        return{
                            time: parseInt(RegExp.$1)*60 + parseFloat(RegExp.$2),
                            lyric: RegExp.$3
                        }
                    }
                });
                this.lyric = newLyric;
            }).catch(err=>{
                console.log(err);
            });
        }
    }
}
</script>

<style lang="less" scoped>
.player{
    width: 100%;
    position: fixed;
    z-index: 10;
    bottom: 0px;
    background-color: rgba(216, 212, 212, 0.9);
    audio{
        height: 50px;
    }
    .playBar{
        display: flex;
        align-items: center;
        padding: 5px;
        &>i{
            &:first-of-type{
                width: 50px;
                height: 50px;
                border-radius: 50%;
                overflow: hidden;
                animation: randImg 5s linear infinite;
                img{
                    width: 100%;
                    height: 100%;
                }
            }
            &:nth-of-type(2){
                display: -webkit-box;
                -webkit-line-clamp: 1;
                -webkit-box-orient: vertical;
                overflow: hidden;
                height: 50px;
                line-height: 50px;
                flex: 1;
                text-align: center;
                font-style: normal;
            }
            &:nth-of-type(3){
                width: 50px;
                height: 50px;
            }
            &:nth-of-type(4){
                width: 50px;
                height: 50px;
            }
        }
    }
    .fullPage{
        width: 100vw;
        height: 100vh;
        // background-color:rgba(0, 0, 0, 0.9);
        position: relative;
        .bg{
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
            filter: brightness(0.5);
            img{
                filter: blur(8px);
                width: 100%;
                height: 100%;
                vertical-align: baseline;
            }
        }
        .needle{
            width: 110px;
            height: 157px;
            position: absolute;
            top: 0px;
            left: 50%;
            margin-left: -20px;
            z-index: 20;
            background: url(../assets/img/needle-ip6.png) no-repeat;
            background-size: cover;
            transition: all .5s;
            transform-origin: left top;
            transform: rotate(-30deg);
        }
        .back{
            margin-left: 10px;
            margin-top: 10px;
            width: 30px;
            height: 30px;
            font-size: 30px;
            display: inline-block;
            color: white;
        }
        .comment{
            margin-right: 10px;
            margin-top: 10px;
            float: right;
            font-size: 30px;
            color: white;
        }
        .like{
            margin-right: 10px;
            margin-top: 10px;
            float: right;
            font-size: 30px;
            color: #dd001b;
        }
        .songImg{
            display: flex;
            justify-content: center;
            align-items: center;
            width: 100%;
            span{
                display: flex;
                justify-content: center;
                align-items: center;
                width: 294px;
                height: 294px;
                background: url(../assets/img/disc.png);
                background-size: cover;
                animation: randImg 20s linear 0s infinite;
                img{
                    width: 178px;
                    height: 178px;
                    border-radius: 50%;
                }
            }
        }
        .lyric,.nolyric{
            padding-top: 10px;
            text-align: center;
            color: white;
            height: 35vh;
            overflow: hidden;
            position: relative;
            &.lyricFull{
                position: absolute;
                z-index: 999;
                top: 0px;
                width: 100vw;
                height: 100vh;
                background-color:rgba(32, 32, 32, 0.9);
                h3{
                    height: 10vh;
                    line-height: 10vh;
                }
                div{
                    height: 82vh;
                    padding-bottom: 20px;
                }
            }
            h3{
                height: 4vh;
                font-size: 18px;
                color: white;
                margin-bottom: 10px;
                width: 100%;
            }
            div{
                overflow: hidden;
                ul{
                li{
                    color: #a09393;
                    &.active{
                        color: #D2C0A5;
                        line-height: 40px;
                    }
                }
            }
            p{
                color: #D2C0A5;
                line-height: 40px;
            }
            }
        }
        .progress{
            position: fixed;
            bottom: 80px;
            display: flex;
            justify-content: space-around;
            width: 100vw;
            color: white;
            text-align: center;
            i{
                font-style: normal;
                width: 20%;
            }
            input{
                width:60%;
            }
        }
        .controlBar{
            position: fixed;
            bottom: 0px;
            width: 100vw;
            height: 70px;
            display: flex;
            justify-content: space-c;
            align-items: center;
            span{
                text-align: center;
                flex: 1;
                color: white;
                font-size: 26px;
                cursor: pointer;
                &:nth-of-type(3){
                    font-size: 46px;
                }
            }
        }
        .playList{
            width: 96vw;
            height: 40vh;
            border-radius: 10px;
            overflow-y: auto;
            z-index: 20;
            position: fixed;
            left: 2vw;
            bottom: 10px;
            box-shadow: 0px 0px 10px #ddd;
            background-color: rgb(255, 255, 255);
            transition: all .5s;
            transform: translateY(150%);
            &.active{
                transform: translateY(0%);
            }
            p{
                height: 6vh;
                color: #df3436;
                padding: 10px 10px ;
                span{
                    font-size: 18px;;
                    float: right;
                }
            }
            ul{
                li{
                    padding: 2px 10px;
                    position: relative;
                    span{
                        color: black !important;
                    }
                }
            }
        }
    }
}
@keyframes randImg {
    0%{
        transform: rotate(0deg);
    }
    100%{
        transform: rotate(360deg);
    }
}
.lyricTitle{
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
}
</style>